package com.wuyan.web.base.helper.convert;

import com.wuyan.helper.kit.endecryption.DecryptionHelper;
import com.wuyan.helper.kit.endecryption.EncryptionHelper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.persistence.AttributeConverter;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * AttributeConverter: 此接口用于转化实体属性的
 * 用于对数据进行加密或者解密,可逆: 选取AES
 */

@Slf4j
public class EncryptionReversibleConvert implements AttributeConverter<String, String> {

    /**
     * 密钥
     */
    private static final String secret = "wuyan-202103221930";

    @SneakyThrows
    @Override
    public String convertToDatabaseColumn(String value) {
        return encode(value);
    }

    @SneakyThrows
    @Override
    public String convertToEntityAttribute(String value) {
        return decode(value);
    }

    /**
     * 加密
     *
     * @param value 需要加密的字符串
     * @return String
     * @throws InvalidKeyException       e
     * @throws NoSuchAlgorithmException  e
     * @throws NoSuchPaddingException    e
     * @throws BadPaddingException       e
     * @throws IllegalBlockSizeException e
     */
    public static String encode(Object value) throws InvalidKeyException, NoSuchAlgorithmException,
            NoSuchPaddingException, BadPaddingException,
            IllegalBlockSizeException {
        if (null == value) {
            return null;
        }

        return EncryptionHelper.getInstance().encodeAES(value.toString(), secret);
    }

    /**
     * 解密
     *
     * @param value 已
     * @return String
     * @throws InvalidKeyException       e
     * @throws NoSuchAlgorithmException  e
     * @throws NoSuchPaddingException    e
     * @throws BadPaddingException       e
     * @throws IllegalBlockSizeException e
     */
    public static String decode(Object value) throws InvalidKeyException, NoSuchAlgorithmException,
            NoSuchPaddingException, BadPaddingException,
            IllegalBlockSizeException {
        if (null == value) {
            return null;
        }

        return DecryptionHelper.getInstance().decodeAES(value.toString(), secret);
    }
}
